<?php

namespace App\Sys\Services;

use App\Services\CommonBaseService;


class SysMenuFuncService extends CommonBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'SysMenuFunc:';

    protected $tokenBucket = 'Token:';

    protected $activeBucket = "Active:";

    /**
     * 保存菜单
     * */
    public function saveMenuFunc($params)
    {
        $ret = ['code' => 0, 'data' => 0];
        $data = array();
        $data['menu_func_name'] = $params['menu_func_name'];
        $data['p_id'] = empty($params['p_id']) ? 0 : $params['p_id'];
        $data['type'] = empty($params['type']) ? 0 : $params['type'];
        $data['route_path'] = empty($params['route_path']) ? '' : $params['route_path'];
        $data['update_time'] = nowTime();
        $checkRet = $this->checkMenuFunc($params);
        if ($checkRet['code'] === 0) {
            if (!empty($params['id'])) {
                $id = $params['id'];
                $data['id'] = $id;
                $this->model->where('id', $id)->update($data);
            } else {
                $data['create_time'] = nowTime();
                $id = $this->model->insertGetId($data);
            }
            $ret['data'] = $id;
            $allPath=$this->getMenuFuncAllPath($id);
            if($allPath){
                $this->model->where('id', $id)->update(['path'=>$allPath['path'],'path_name'=>$allPath['path_name']]);
                $this->updateSubAllPath($id);
            }
        } else {
            $ret['code'] = $checkRet['code'];
        }

        return $ret;
    }

    /**
     * 修改菜单状态
     * */
    public function setStatus($id, $status)
    {
        $data = [];
        $data['update_time'] = nowTime();
        $data['status'] = $status;
        $ret = $this->model->where('id', $id)->update($data);
        return $ret;
    }

    /**
     * 获取后台菜单列表
     * */
    public function getMenuFuncList($params)
    {
        $pageSize = empty($params['page_size']) ? 10 : $params['page_size'];
        $page = empty($params['page']) ? 1 : $params['page'];
        $skip = ($page - 1) * $pageSize; //页面记录的开始位置，即偏移量
        $where = [];
        $where[] = ['a.status', '<', '2'];
        $query = $this->model->alias('a')->where($where);
        if (!empty($params['keyword'])) {
            $keyword = $params['keyword'];
            $query->where('a.menu_func_name', 'like', "%" . $keyword . "%");
        }
        if(isset($params['type'])){
            $type=empty($params)?0:$params['type'];
            $query->where('a.type','=',$type);
        }
        $totalCount = $query->count();
        $list = $query->skip($skip)
            ->limit($pageSize)
            ->get()->toArray();
        $results = buildPage($list, $skip, $page, $pageSize, $totalCount);
        return $results;
    }

    /**
     * 角色保存验证 验证通过返回 true 失败返回 false
     * return array
     * */
    private function checkMenuFunc($params)
    {
        $ret = ['code' => 0];
        $routePath = $params['route_path'];
        if (!empty($params['id'])) {
            $id = $params['id'];
            $query = $this->model
                ->where('id', '<>', $id)
                ->where('status', '<', 2)
                ->where('route_path', '=', $routePath);
            $info = $query->first();
        } else {
            $query = $this->model
                ->where('status', '<', 2)
                ->where('route_path', '=', $routePath);
            $info = $query->first();
        }
        if ($info) {
            $info = $info->toArray();
            if ($info['route_path'] == $routePath) {
                $ret['code'] = 11011;
            }
        }
        return $ret;
    }

    /**
     * 获取功能/菜单的全路径
     * */
    public function getMenuFuncAllPath($id){
        $ret=['path'=>'','path_name'=>''];
        $info= $this->model->alias('a')
            ->leftJoin($this->model->getTable().' as b', 'a.p_id', '=', 'b.id')
            ->where('a.id',$id)
            ->where('a.status',0)
            ->selectRaw("b.id as p_id,b.menu_func_name as 'p_name',a.id,a.menu_func_name")
            ->first();
        if($info){
            $info=$info->toArray();
            if(!empty($info['p_id'])){
                $pRet=$this->getMenuFuncAllPath($info['p_id']);
                $ret['path']=$pRet['path'].','.$info['id'];
                $ret['path_name']=$pRet['path_name'].','.$info['menu_func_name'];
            }else{
                $ret['path']= $info['id'];
                $ret['path_name']= $info['menu_func_name'];
            }

        }
        return $ret;

    }

    /**
     * 更新子集的全路径
     * */
    public function updateSubAllPath($id){
        if($id>0){
            $list= $this->model->alias('a')
                ->where('a.p_id',$id)
                ->where('a.status',0)
                ->get();
            if(!empty($list)){
                $list=$list->toArray();
                foreach ($list as $value){
                    $allPath=$this->getMenuFuncAllPath($value['id']);
                    if($allPath){
                        $this->model->where('id', $value['id'])->update(['path'=>$allPath['path'],'path_name'=>$allPath['path_name']]);
                        $this->updateSubAllPath($value['id']);
                    }
                }
            }
        }
    }
}
